﻿/*
 * @Autor: PK
 * @Date: 2021/12/29 17:15:SS
 */

using System;
using System.Collections;
using System.Collections.Generic;
using ShkSimulation.core.dao.statistic;
using ShkSimulation.core.dao.statistic.feature;
using ShkSimulation.core.util;

namespace ShkSimulation.core.dao.output.result {

	public class ResultData : IEnumerable<KeyValuePair<string, CollectionReportData>> {

		private CollectionReportData data;

		public int Count => Data.Count;

		public Dictionary<string, CollectionReportData> Data { get; set; } =
			new Dictionary<string, CollectionReportData>();
		
		public CollectionReportData FlatData {
			get {
				if (this.data != null) {
					return this.data;
				}
				Dictionary<VariableAndHourStatisticKey, StatisticInfo> flatData = new Dictionary<VariableAndHourStatisticKey, StatisticInfo>();
				foreach (var (collectionUniqueKey, values) in Data) {
					foreach ((VariableAndHourStatisticKey key, StatisticInfo value) in values) {
						if (flatData.ContainsKey(key)) {
							string temp = $"{key.VariableName}#{collectionUniqueKey}";
							VariableAndHourStatisticKey newKey = new VariableAndHourStatisticKey(temp, $"{key.HourStatisticName}");
							flatData.Add(newKey, value);
						} else {
							flatData.Add(key, value);
						}
					}
				}
				CollectionReportData collectionReportData = CollectionReportData.Create("FlatData", flatData);
				this.data = collectionReportData;
				return collectionReportData;
			}
		}

		public DateTime ReportTime { get; init; }

		public ResultData AddResultData(ResultData second) {
			var temp = new Dictionary<string, CollectionReportData>(Data);
			temp.AddRange(second.Data);
			ResultData resultData = new ResultData();
			resultData.Data = temp;
			return resultData;
		}
		
		public StatisticInfo GetStatisticInfoByFlatData(string variableName, string hourStatisticName = null) {
			return FlatData.GetStatisticInfo(variableName, hourStatisticName);
		}

		public StatisticInfo GetStatisticInfoByFlatData(VariableAndHourStatisticKey key) {
			return FlatData.GetStatisticInfo(key);
		}

		public bool ContainsKey(string key) {
			return Data.ContainsKey(key);
		}

		public CollectionReportData this[string key] {
			get { return Data[key]; }
			set => Data[key] = value;
		}

		public IEnumerator<KeyValuePair<string, CollectionReportData>> GetEnumerator() {
			return Data.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator() {
			return GetEnumerator();
		}

	}

}